package impl.service;

import tools.Feature;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MusicServer {
    private ServerSocket serverSocket = null;

    public MusicServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("数据传输服务器启动!");

        while (true) {
            Socket clientSocket = serverSocket.accept();
            ExecutorService pool = Executors.newFixedThreadPool(1);
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }
    public void processConnection(Socket clientSocket) {
        System.out.printf("[%s:%d] 客户端上线,已连接音乐服务器!\n", clientSocket.getInetAddress(), clientSocket.getPort());
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.UTF_8));
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream(), StandardCharsets.UTF_8))) {

            String request = reader.readLine();
            Object response = process(request);
            writer.write(response.toString());
            writer.newLine();
            writer.flush();
            System.out.printf("[%s:%d] req=%s, resp=%s\n", clientSocket.getInetAddress(), clientSocket.getPort(), request, response);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
                System.out.printf("[%s:%d] 客户端下线!\n", clientSocket.getInetAddress(), clientSocket.getPort());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public Object process(String request) {
        String[] a = request.split(";");
        String[] b = new String[2];
        for (int i = 0; i < a.length; i++) {
            String[] c = a[i].split(":");
            b[i] = c[1];
        }
        String type = b[0];
        Map<String,String> data = new HashMap<>();
        String[] c = b[1].split("-");
        for (int i = 0; i < c.length; i++) {
            String[] d = c[i].split("=");
            data.put(d[0],d[1]);
        }

        return new Feature().result(type,data);
    }
}

